//
//  CmtProductDetailViewController.m
//  Products_B
//
//  Created by lanou on 16/6/6.
//  Copyright © 2016年 朋学友. All rights reserved.
//

#import "CmtProductDetailViewController.h"
#import "CmtAttentionTableViewController.h"


#import "CommunityViewController.h"
#define kCmtSecAttenDetailUrlString @"http://api.izhangchu.com/"
#import "RequestManager.h"
#import <UIImageView+WebCache.h>

#import "CmtSecAttenModel.h"
#import "CmtSecAttenComment.h"
#import "CmtSecAttenLike.h"
#import "CmtSecAttenRelates.h"

#import "CmtSecAttenDetailSTableViewCell.h"
#import "CmtSecDetailTableViewCell.h"
@interface CmtProductDetailViewController ()<UITableViewDataSource,UITableViewDelegate,UIWebViewDelegate,UIScrollViewDelegate>
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)CmtSecAttenModel *model;

@property(nonatomic ,strong)NSMutableArray *modelArray;
@property(nonatomic, strong)NSMutableArray *likeArray;
@property(nonatomic ,strong)NSMutableArray *commentArray;
@property(nonatomic,strong)NSMutableArray *relatesArray;

@property(nonatomic,strong) UIView *headView;

@property(nonatomic,strong)UIImageView *coverimg;

@property(nonatomic,strong)UIWebView *webView;
@property(nonatomic,strong)UIImageView *head_image;
@property(nonatomic,strong)UILabel *nickLabel;
@property(nonatomic,strong)UILabel *createLabel;

@property(nonatomic,strong)UIView *topView;

@property(nonatomic,strong)UIView *downView;

@property(nonatomic,assign)int page;
@property(nonatomic,assign)CGPoint OldContentOffset;
@property(nonatomic,assign)CGPoint NewContentOffset;
@property(nonatomic,assign)CGPoint ContentOffset;

//@property(nonatomic,strong)UIView *topView;
@end

@implementation CmtProductDetailViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
     self.topView.hidden = NO;
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];

    self.topView.hidden = YES;
}


//自定义导航栏
-(void)setNavView{
    self.topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kWidth, 70)];
    UIButton *button = [UIButton buttonWithType:(UIButtonTypeSystem)];
    _topView.backgroundColor = [UIColor whiteColor];
    button.frame = CGRectMake(10, 30, 50, 30);
    [button setTitle:@"<—" forState:(UIControlStateNormal)];
    [button addTarget:self action:@selector(buton:) forControlEvents:(UIControlEventTouchUpInside)];
    [_topView addSubview:button];
    [self.navigationController.view addSubview:_topView];
    
    UIButton *shareButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
    shareButton.frame = CGRectMake(kWidth - 120, 30, 50, 30);
    [shareButton setImage:[UIImage imageNamed:@"share.png"] forState:(UIControlStateNormal)];
    [shareButton addTarget:self action:@selector(shareAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.topView addSubview:shareButton];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake((kWidth - 80)/2, 30, 80, 30)];
    label.text = @"作品详情";
    label.textAlignment = NSTextAlignmentCenter;
    [self.topView addSubview:label];
    
    UIButton *collectButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
    collectButton.frame = CGRectMake(kWidth - 70, 30, 50, 30);
    [collectButton setImage:[UIImage imageNamed:@"CmtCollect.png"] forState:(UIControlStateNormal)];
    [collectButton addTarget:self action:@selector(shareAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.topView addSubview:collectButton];
    
//    self.tableView.frame = CGRectMake(0, 5, kWidth, kHeight - 5);
    
//    self.tableView.backgroundColor = [UIColor redColor];
    self.view.backgroundColor = [UIColor yellowColor];
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    加导航栏
    [self setNavView];
    
//    创建tableView
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kWidth, kHeight) style:(UITableViewStylePlain)];
    [self.view addSubview:_tableView];
//   设置代理
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[CmtSecDetailTableViewCell class] forCellReuseIdentifier:@"reuseIdentifier"];
    [self.tableView registerClass:[CmtSecAttenDetailSTableViewCell class] forCellReuseIdentifier:@"CmtSecSCell"];
//   初始化数组
    self.likeArray = [NSMutableArray arrayWithCapacity:10];
    self.commentArray = [NSMutableArray arrayWithCapacity:10];
    self.relatesArray = [NSMutableArray arrayWithCapacity:10];
    self.modelArray = [NSMutableArray arrayWithCapacity:10];
//    初始化webView
    self.webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, kWidth, kWidth, 10)];
    _webView.backgroundColor = [UIColor greenColor];
    _webView.delegate = self;
    
    
    self.headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kWidth, 600)];
    self.tableView.tableHeaderView = _headView;
    
    self.page = 1;
    [self requestCmtSecDataWithUrlString:kCmtSecAttenDetailUrlString];
    [self requestDataComment];

   
    //    上拉加载更多
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.page += 1;
        [self.modelArray removeAllObjects];
        [self.likeArray removeAllObjects];
        [self requestDataComment];
    }];
    //  下拉刷新
    self.tableView.mj_header = [MJRefreshHeader headerWithRefreshingBlock:^{
        self.page = 1;
        [self.modelArray removeAllObjects];
        [self.likeArray removeAllObjects];
        [self requestDataComment];
        
    }];
    [self initDownView];
}


//向下滑的弹窗
-(void)initDownView{
    
    self.downView = [[UIView alloc]initWithFrame:CGRectMake(0, kHeight - 50, kWidth, 50)];
    self.downView.backgroundColor = PKCOLOR(251, 241, 231);
    [self.view addSubview:_downView];
    self.downView.hidden = YES;
    UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
    button.frame = CGRectMake((kWidth - 40) / 2, 0, 40, 40);
    [button setImage:[UIImage imageNamed:@"CmtCamera.png"] forState:(UIControlStateNormal)];
    [button addTarget:self action:@selector(CameraAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.downView addSubview:button];
}

-(void)CameraAction:(UIButton *)button{
    NSLog(@"点击了按钮");
}


-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    NSLog(@"开始拖拽%lf",scrollView.contentOffset.y);
    self.ContentOffset = scrollView.contentOffset;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    //    NSLog(@"滚动%lf",scrollView.contentOffset.y);
    self.NewContentOffset = scrollView.contentOffset;
    
    //    向下滑动
    if (self.NewContentOffset.y > self.ContentOffset.y | self.NewContentOffset.y > self.OldContentOffset.y) {
        NSLog(@"向下滑");
        
        self.downView.hidden = YES;
        
    }else{
        
        NSLog(@"向上滑");
        self.downView.hidden = NO;
    }
    
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSLog(@"开始减速%lf",scrollView.contentOffset.y);
    self.OldContentOffset = scrollView.contentOffset;
}



//评论列表的数据请求
-(void)requestDataComment{
    
    NSDictionary *parDic = @{@"relate_id":self.post_id,@"type":@"3",@"page":[NSString stringWithFormat:@"%d",self.page],@"methodName":@"CommentList",@"size":@"20",@"version":@"4.40&"};
    
    [RequestManager requestWithUrl:kCmtSecAttenDetailUrlString requestType:(RequestTypePOST) parDic:parDic finish:^(NSData *data) {
        
        NSDictionary *jsdic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        [self.commentArray removeAllObjects];
        self.commentArray = [CmtSecAttenComment setModelWithJsDic:jsdic];
        
        [self.tableView reloadData];
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
        
    } error:nil];
}

//请求表头的数据
-(void)requestCmtSecDataWithUrlString:(NSString *)urlString{
    
    NSDictionary *parDic = @{@"post_id":self.post_id,@"methodName":@"ShequPostview",@"version":@"4.40&"};
    [RequestManager requestWithUrl:urlString requestType:(RequestTypePOST) parDic:parDic finish:^(NSData *data) {
        NSDictionary *jsDic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        //        NSLog(@"%@",jsDic);
        
        self.modelArray = [CmtSecAttenModel setModelWithJsDic:jsDic];
        
        for (CmtSecAttenModel *model in _modelArray) {
            
            for (CmtSecAttenLike *likeModel in model.likeArray) {
                [_likeArray addObject:likeModel];
            }
            for (CmtSecAttenRelates *relateModel in model.relatesArry) {
                
                [_relatesArray addObject:relateModel];
            }
            self.model = model;
            [_webView loadHTMLString:model.content baseURL:nil];
            
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];

        }
        
    } error:nil];
    
}

//布局表头
-(void)setHeadView{
    
    self.coverimg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, kWidth, kWidth)];
    _coverimg.backgroundColor = [UIColor yellowColor];
    
    self.head_image = [[UIImageView alloc]initWithFrame:CGRectMake(20, kWidth + _webView.frame.size.height + 20, 50, 50)];
    _head_image.layer.cornerRadius = 25;
    _head_image.layer.masksToBounds = YES;
    
    self.nickLabel = [[UILabel alloc]initWithFrame:CGRectMake(80, kWidth + _webView.frame.size.height + 20, 100, 25)];
    _nickLabel.font = [UIFont systemFontOfSize:15];
    
    
    self.createLabel = [[UILabel alloc]initWithFrame:CGRectMake(80, kWidth +  self.webView.frame.size.height + 40, 100, 25)];
    _createLabel.font = [UIFont systemFontOfSize:15];
    [_headView addSubview:_coverimg];
    [_headView addSubview:_head_image];
    [_headView addSubview:_nickLabel];
    [_headView addSubview:_createLabel];
    [_headView addSubview:_webView];
    
    [self.tableView setTableHeaderView:_headView];
    
}


//加载表头
-(void)loadHeadViewWithModel:(CmtSecAttenModel *)model{
    
    [_coverimg sd_setImageWithURL:[NSURL URLWithString:model.image]];
    _nickLabel.text = model.nick;
    [_head_image sd_setImageWithURL:[NSURL URLWithString:model.head_img]];
    _createLabel.text = model.create_time;
    
}

//webView的动态高度返回
-(void)webViewDidFinishLoad:(UIWebView *)webView{
    
    CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"] floatValue];
    
    //  改变webView的高度
    CGRect newFrame = webView.frame;
    newFrame.size.height  = height;
    webView.frame = newFrame;
    
    CGRect newHeadViewFrame = self.headView.frame;
    
    newHeadViewFrame.size.height = (CGFloat)(kWidth + webView.frame.size.height + 100);
    self.headView.frame = newHeadViewFrame;
    [self.tableView setTableHeaderView:_headView];
    
    [self setHeadView];
    
    [self loadHeadViewWithModel:self.model];
}



//分享按钮
-(void)shareAction:(UIButton *)button{
    
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //    评论列表加两个row
    return _commentArray.count + 2;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        //            点赞和相关作品的Cell
        CmtSecDetailTableViewCell *cell = [[CmtSecDetailTableViewCell alloc]init];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [cell setCellWithModel:_model withTapBlock:^(int index){
        
            }];
            
        });

        
        return cell;
    }
    
    //        发表评论的Cell
    if (indexPath.row == 1) {
        CmtSecDetailTableViewCell *cell = [[CmtSecDetailTableViewCell alloc]init];
        CmtSecAttenComment *comment = self.commentArray.firstObject;
        
        [cell setCommentCellWithModel:comment withTapBlock:^(int index){
            
            NSLog(@">>>>>>>>>>><<<<<<<<<<<");
            
        }];
        return cell;
    }
    
    //   评论列表的Cell
    CmtSecAttenDetailSTableViewCell *Scell = [tableView dequeueReusableCellWithIdentifier:@"CmtSecSCell" forIndexPath:indexPath];
    CmtSecAttenComment *Comment = _commentArray[indexPath.row - 2];
    Scell.model = Comment;
    return Scell;
    
}

//隐藏tabBar
- (id)init {
    self = [super init];
    if (self) {
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}
//返回Cell的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return 180;
    }if (indexPath.row == 1) {
        return 100;
    }
    return 100;
}



//重写假导航栏的返回
-(void)buton:(UIButton*)sender{
    
    [self.navigationController popViewControllerAnimated:YES];
    
    self.navigationController.navigationBarHidden = YES;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
